package standalone

import (
	"github.com/DiracLee/dires-go/app/cmdline"
	"github.com/DiracLee/dires-go/app/connection"
	"github.com/DiracLee/dires-go/app/handler"
	"github.com/DiracLee/dires-go/app/payload"
	"strings"
)

func execNormal(svr *Standalone, conn connection.Connection, cmdLine cmdline.CmdLine) payload.Payload {
	db, ok := selectDB(svr, conn)
	if !ok {
		return payload.NewErrPayload("ERR Storage Index is out of range")
	}
	if conn != nil && conn.InMultiState() {
		EnqueueCmd(conn, cmdLine)
		return payload.NewQueuedPayload()
	}
	cmdName := strings.ToLower(string(cmdLine[0]))
	cmd, ok := handler.CmdTable[cmdName]
	if !ok {
		return payload.NewErrPayload("ERR unknown command '" + cmdName + "'")
	}
	if !validateArity(cmd.Arity, cmdLine) {
		return payload.NewArgNumErrPayload(cmdName)
	}

	prepare := cmd.Prepare
	write, read := prepare(cmdLine[1:])
	db.AddVersion(write...)
	db.RWLock(write, read)
	defer db.RWUnlock(write, read)
	exec := cmd.Executor
	return exec(db, cmdLine[1:])
}
